<template>
  <div class="person-div">
    <el-form :inline="true" :model="search" class="demo-form-inline">
      <el-form-item label="用戶名称：" width="20%">
        <el-input v-model="search.username" placeholder="请输入用户名称"></el-input>
      </el-form-item>
      <el-form-item label="手机号码：">
        <el-input v-model="search.phonenum" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="职级">
        <el-select v-model="search.rank" placeholder="请选择用户职级">
          <el-option label="一级" value="一级"></el-option>
          <el-option label="二级" value="二级"></el-option>
          <el-option label="三级" value="三级"></el-option>
          <el-option label="四级" value="四级"></el-option>
          <el-option label="五级" value="五级"></el-option>
          <el-option label="六级" value="六级"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="职类">
        <el-select v-model="search.category" placeholder="请选择用户职类">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchGo()">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh()" plain>重置</el-button>
      </el-form-item>
      <div>
        <el-button v-if="auths.useradd!=null" type="primary" icon="el-icon-plus" @click="dialogVisible = true">添加用户</el-button>
        <el-button v-if="auths.userdelete!=null" type="primary" icon="el-icon-delete" :disabled="deleteButton" @click="deleteUserByList()">批量删除
        </el-button>
      </div>
    </el-form>

    <!-- 添加用户    -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%">
      <el-form ref="Rulesform" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入用户账号"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenum">
          <el-input v-model="form.phonenum" placeholder="请输入用户手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入用户密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="职类" prop="category">
          <el-select v-model="form.category" placeholder="请选择用户职类">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职级" prop="rank">
          <el-select v-model="form.rank" placeholder="请选择用户职级">
            <el-option label="一级" value="一级"></el-option>
            <el-option label="二级" value="二级"></el-option>
            <el-option label="三级" value="三级"></el-option>
            <el-option label="四级" value="四级"></el-option>
            <el-option label="五级" value="五级"></el-option>
            <el-option label="六级" value="六级"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!--  修改用户   -->
    <el-dialog title="修改信息" :visible.sync="changeVisible" width="30%"
               :before-close="handleClose"
    >
      <el-form ref="form" :model="changemessage" label-width="80px" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="changemessage.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenum">
          <el-input v-model="changemessage.phonenum" placeholder="请输入用户手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="changemessage.password" placeholder="请输入用户密码" show-password></el-input>
        </el-form-item>

        <el-form-item label="职类" prop="category">
          <el-select v-model="changemessage.category" placeholder="请选择用户职类">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职级" prop="rank">
          <el-select v-model="changemessage.rank" placeholder="请选择用户职级">
            <el-option label="一级" value="一级"></el-option>
            <el-option label="二级" value="二级"></el-option>
            <el-option label="三级" value="三级"></el-option>
            <el-option label="四级" value="四级"></el-option>
            <el-option label="五级" value="五级"></el-option>
            <el-option label="六级" value="六级"></el-option>
          </el-select>
        </el-form-item>
      </el-form>


      <span slot="footer" class="dialog-footer">
        <el-button @click="changeVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeUserMessage">确 定</el-button>
      </span>
    </el-dialog>

    <!--  给用户分配角色  -->
    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible" width="40%">
      <el-transfer
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入角色名称"
        v-model="rolevalue"
        :data="roledata"
        :titles="['未有角色', '已有角色']"
      >
      </el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelRoledhe()">取 消</el-button>
        <el-button type="primary" @click="addRoleToUserInfo()">确 定</el-button>
      </span>
    </el-dialog>


    <el-table :data="tableData" @selection-change="selectionChange()" @select="selectRow" @select-all="selectAll"
              style="width: 100%"
    >
      <el-table-column type="selection" width="45"></el-table-column>
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column prop="username" label="用户名称" width="180"></el-table-column>
      <el-table-column prop="account" label="用户账号"></el-table-column>
      <el-table-column prop="phonenum" label="手机号"></el-table-column>
      <el-table-column prop="category" label="用户职类"></el-table-column>
      <el-table-column prop="rank" label="用户职级"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="200"></el-table-column>
      <el-table-column prop="gmtModified" label="修改时间" width="200"></el-table-column>
      <el-table-column prop="handle" label="操作" width="200">
        <template slot-scope="scope">
          <el-button v-if="auths.projectlist!=null" type="success"  icon="el-icon-user-solid" :title="assignRole" size="mini" @click="showRoleList(scope.row)"></el-button>
          <el-button v-if="auths.userupdate!=null" type="primary" size="mini" icon="el-icon-edit" :title="updateUser" @click="responesChange(scope.row)"></el-button>
          <el-button v-if="auths.userdelete!=null" type="danger" size="mini" icon="el-icon-delete" :title="deleteUser" @click="open(scope.row.uid)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--   分页 页码  -->
    <div class="block" style="margin-top:15px;">
      <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryparams.page"
        :page-sizes="[5,10,20,50]"
        :page-size="queryparams.offset"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import {
  searchByParam, getUserList,
  deleteUserById, updateUserById, insertUser, deleteUserByList, getUserRoles,addRolesToUser
} from '@/api/user'
import { getAuths } from '@/utils/auth'

export default {

  data() {
    //自定义下拉框校验函数
    const isSelect = (rule, value, callback) => {
      if (value == 0) { //如果值是 0，提示用户选择正确的选项
        return callback(new Error('请正确选择一级标题'))
      } else {
        callback()
      }
    }

    return {
      auths:'',
      assignRole:'分配角色',
      updateUser:'修改用户信息',
      deleteUser:'删除用户信息',
      allroles: [],
      roledata: [],
      rolevalue: [],
      filterMethod(query, item) {
        return item.pinyin.indexOf(query) > -1
      },

      dialogRoleVisible: false,
      isClickSelectAll: false,
      searchflag: false,
      search: {
        username: '',
        phonenum: '',
        category: '',
        rank: '',
        page: 1,
        offset: 10
      },
      // 需要删除的用户列表
      deleteList: [],

      deleteButton: true,

      queryparams: {
        page: 1,
        offset: 10
      },

      formInline: {
        username: '',
        account: '',
        phonenum: '',
        category: '',
        gmt_create: '',
        gmt_modified: '',
        currentPage: 4
      },
      dialogVisible: false,   // 控制添加用户框
      changeVisible: false,   // 控制修改框
      form: {
        username: '',
        password: '',
        account: '',
        phonenum: '',
        category: '',
        rank: ''
      },
      rules: {
        username:
          [{ required: true, message: '请输入用户名', trigger: 'blur' },
            {
              validator: function(rule, value, callback) {
                //校验中文的正则：/^[\u4e00-\u9fa5]{0,}$/
                if (/^[\u4e00-\u9fa5]{0,}$/.test(value) == false) {
                  callback(new Error('请输入中文'))
                } else {
                  //校验通过
                  callback()
                }
              }, trigger: 'blur'
            }
          ],
        account: [{ required: true, message: '请输入账号', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              //校验中文的正则：/^[\u4e00-\u9fa5]{0,}$/
              if (/^[a-zA-Z][a-zA-Z0-9]{4,15}$/.test(value) == false) {
                callback(new Error('请输入只含有数字、字母的账号（字母开头，允许5-20字节）'))
              } else {
                //校验通过
                callback()
              }
            }, trigger: 'blur'
          }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              //校验中文的正则：/^[\u4e00-\u9fa5]{0,}$/
              if (/(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{6,20}$/.test(value) == false) {
                callback(new Error('6位以上密码,数字,字母,字符至少包含两种,不能包含中文和空格'))
              } else {
                //校验通过
                callback()
              }
            }, trigger: 'blur'
          }],
        phonenum: [{ required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error('请输入正确的手机号'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }],
        category: [{ required: true, trigger: 'change', validator: isSelect }],
        rank: [{ required: true, trigger: 'change', validator: isSelect }]
      },
      changemessage: {
        uid: '',
        rank: '',
        username: '',
        password: '',
        phonenum: '',
        category: ''
      },
      options: [
        {
          value: 'Java工程师',
          label: 'Java工程师'
        },
        {
          value: '测试工程师',
          label: '测试工程师'
        },
        {
          value: '.Net工程师',
          label: '.Net工程师'
        },
        {
          value: '系统架构师',
          label: '系统架构师'
        },
        {
          value: '网络工程师',
          label: '网络工程师'
        }
      ],
      value: '',
      tableData: [],
      total: 0, // 总条数
      userrolesid:0

    }
  },
  created() {
    this.auths = JSON.parse(getAuths())
    // console.log(this.auths.userlist==null)
    this.getUserData()

  },
  methods: {

    generateData(){
      const data = []
      for (let i = 0; i < this.allroles.length; i++) {
        data.push({
          label: this.allroles[i].rname,
          key: this.allroles[i].rid,
          pinyin: this.allroles[i].rname
        })
      }
      return data
    },
    showRoleList(row) {
      this.userrolesid = row.uid
      this.dialogRoleVisible = true
      let url = '/get/all/roles/' + row.uid
      getUserRoles(url).then((res) => {
        this.allroles = res.data.roles
        this.roledata = this.generateData()
        res.data.checkedroles.forEach((item)=>{
          this.rolevalue.push(item.rid)
        })
      })
    },

    /**
     * 给用户添加角色
     */
    addRoleToUserInfo() {
      this.dialogRoleVisible = false
      let url = '/update/user/roles/'+this.userrolesid
      addRolesToUser(url,this.rolevalue).then((res)=>{
        // 这里是回调函数
        if (res.code != 200) return this.changeUserInfoSuccess('失败', '添加用户失败！')
        this.changeUserInfoSuccess('成功', '添加用户成功！')
      })
      this.roledata = []
      this.allroles = []
      this.rolevalue = []
      // console.log(this.rolevalue)
    },
    cancelRoledhe(){
      this.dialogRoleVisible=false
      this.roledata = []
      this.allroles = []
      this.rolevalue = []
    },

    handleClose() {
      this.changeVisible = false
    },
    searchGo() {
      this.searchflag = true
      // 先进行参数校验
      // 发送搜索请求
      searchByParam(this.search).then((res) => {
        if (res.result == 'SUCCESS' && res.code == 200) {
          this.queryparams.page = this.search.page
          this.queryparams.offset = this.search.offset
          this.total = res.data.total
          this.tableData = res.data.data
        }
      })
    },
    refresh() {
      this.search.username = ''
      this.search.phonenum = ''
      this.search.category = ''
      this.search.rank = ''
      this.searchflag = false
      this.getUserData()
    },

    clearForm() {
      this.form.username = ''
      this.form.password = ''
      this.form.account = ''
      this.form.phonenum = ''
      this.form.category = ''
      this.form.rank = ''
    },

    // 批量删除操作
    async deleteUserByList() {
      if (this.deleteList.length === 0) {
        this.$alert('请选择需要删除的用户数据', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
        return
      }
      const confirmResult = await this.$confirm('此操作将永久删除所选项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message({ message: '已取消删除', center: true })
      }
      deleteUserByList(this.deleteList).then(res => {
        this.deleteList = []
        if (res.code !== 200) return this.$message({ message: '删除失败', type: 'error', center: true })
        this.$message({ message: '删除成功', type: 'success', center: true })
        this.getUserData()
      })
    },
    selectionChange() {
      if (this.deleteList.length == 0) {
        this.deleteButton = true
      }
    },
    // 选中单行数据
    selectRow(selection, row) {
      this.deleteList = []
      for (let i = 0; i < selection.length; i++) {
        this.deleteList.push(selection[i].uid)
      }
      this.deleteButton = false
    },

    // 选中全部数据

    selectAll(selection) {
      this.deleteButton=!this.deleteButton;
      console.log('11this.isClickSelectAll', this.isClickSelectAll)
      this.deleteList = []
      for (let i = 0; i < selection.length; i++) {
        this.deleteList.push(selection[i].uid)
      }

    },

    addNewUserInfo() {
      // 添加新用户信息
      this.$refs.Rulesform.validate((valid) => {
        if (valid) {
          insertUser(this.form).then((res) => {
            this.dialogVisible = false
            // 这里是回调函数
            if (res.code != 200) return this.changeUserInfoSuccess('失败', '添加用户失败！')
            this.changeUserInfoSuccess('成功', '添加用户成功！')
            this.clearForm()
            this.getUserData()
          })
        } else {
          this.$message.error('请完善表单相关信息！')
          return false
        }
      })
    },

    changeUserInfoSuccess(title, message) {
      this.$notify({
        title: title,
        message: message,
        type: 'success',
        duration: 2000
      })
    },

    responesChange(user) {  // 响应修改用户按钮
      this.changeVisible = true
      this.changemessage.password = ''
      this.changemessage.rank = user.rank
      this.changemessage.uid = user.uid,
        this.changemessage.username = user.username,
        this.changemessage.phonenum = user.phonenum,
        this.changemessage.category = user.category
    },

    // 修改数据时出发该函数
    changeUserMessage() {
      // 这里需要校验一下数据格式
      this.$refs.form.validate((valid) => {
        if (valid) {
          updateUserById(this.changemessage).then((res) => {
            if (res.result = 'SUCCESS' && res.code == 200) {
              // 请求成功
              this.changeVisible = false

              this.changeUserInfoSuccess('提示', '修改用户成功')

              this.getUserData()  // 刷新数据
            } else {
              this.changeVisible = false
              this.changeUserInfoSuccess('提示', res.message)
            }
          })
        } else {
          this.$message.error('请完善表单相关信息！')
          return false
        }
      })

      // 修改用户信息，发送请求

    },

    getUserData() {
      let url = '/get/usr/info/' + this.queryparams.page + '/' + this.queryparams.offset
      getUserList(url).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
      })
    },

    onSubmit() {
      console.log('submit!')
    },

    changeUser(userid) {
      console.log(userid)
    },
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(newSize) {
      this.queryparams.offset = newSize
      // 重新按照pagesize发送请求，请求最新的数据
      if (this.searchflag) {
        this.search.offset = newSize
        this.searchGo()
        return
      }

      this.getUserData()
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.queryparams.page = val
      if (this.searchflag) {
        this.search.page = val
        this.searchGo()
        return
      }
      this.getUserData()
    },

    open(uid) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 这里发送请求
          let url = 'del/by/' + uid
          deleteUserById(url).then(res => {
            if (res.result === 'SUCCESS' && res.code == 200) {
              this.$message({ type: 'success', message: '删除成功!' })
              this.getUserData() // 重新加载数据
            } else {
              this.$message({ type: 'info', message: '删除失败!' })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style>
.person-div {
  padding-top: 40px;
  padding-left: 40px;
}
</style>
